<?php

namespace app\api\controller\v35;

use app\aliyun\controller\AliyunFilterWord;
use app\api\controller\v2\Auth;
use app\common\cachemodel\ArticleComment;
use app\common\cachemodel\ArticleCommentReply;
use app\common\cachemodel\zl2\Zl2AstrFortuneArticle;
use app\common\cachemodel\zl2\Zl2AstrFortuneArticleZan;
use app\common\cachemodel\ZlUserVip;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\common\model\Recode;
use app\common\model\User;
use app\common\model\UserPush;
use think\Env;
use think\response\Json;
use XznsTools\cache\CacheManage;

class AstrUserFortuneArticle extends Auth
{
    /**
     * 星运变动 动态列表
     * @return Json
     * @throws ApiException
     * @throws \Exception
     */
    public function getArticleList()
    {
        $pid = input('id/d', '');

        $astrCommunityArticleModel = new Zl2AstrFortuneArticle();
        $uid = $this->user ? $this->user['id'] : 0;

        $articlePages = $astrCommunityArticleModel->getListPage($pid, 'id', []);

        $articlePages['data'] = $astrCommunityArticleModel->astrFortuneArticleDataResert($uid, $articlePages['data']);

        return show(config('code.success'), '请求成功', $articlePages);
    }

    /**
     * 星运变动 动态详情
     */
    public function getArticleDetail()
    {
        $id = input('id/d', 0);
        $page = input('page/d', 1);
        $uid = $this->user ? $this->user['id'] : 0;

        if ($id < 1)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        $resData['article_info'] = null;
        $astrFortuneArticleModel = new Zl2AstrFortuneArticle();

        $articleDetail = $astrFortuneArticleModel->getInfoById($id);

        if (!$articleDetail || $articleDetail['status'] !== 0)
        {
            return show(config('code.error'), '服务异常，动态不存在～');
        }

        if ($page === 1)
        {

            if ($articleDetail['uid'] === $uid)
            {
                $nickname = $this->user['nickname'] ?? '';
                $avatar = $this->user['avatar'] ?? '';
                $rid = $this->user['rid'] ?? 0;
                $isSelf = 1;
            } else
            {
                $userInfo = (new User())->getUserinfo(['id' => $articleDetail['uid']]);
                $nickname = $userInfo['nickname'] ?? '';
                $avatar = $userInfo['avatar'] ?? '';
                $rid = $userInfo['rid'] ?? 0;
                $isSelf = 0;
            }

            $userDes = '小行星神秘人';
            if ($rid)
            {
                $recode = (new Recode())->getRecode(['id' => $rid]);
                if ($recode)
                {
                    $utilModel = new Util();
                    $userDes = '日' . $utilModel->recodeAstroShorthand($recode['sun']) . '月' . $utilModel->recodeAstroShorthand($recode['moon']) . '升' . $utilModel->recodeAstroShorthand($recode['asc']);
                }
            }
            // 获取装饰信息
            $adorn = Util::getUserAdorn($articleDetail['uid']);

            $astrCommunityArticleZanModel = new Zl2AstrFortuneArticleZan();
            // 获取用户当前 已赞同 1/已反对 2
            $zanData = $uid > 0 ? $astrCommunityArticleZanModel->getZan($uid, [$id]) : [];

            if ($zanData && !is_array($zanData))
            {
                $zanData = [$id => (int)$zanData];
            }

            $commentBase = $articleDetail['extend']['comment_base'] ?? 0;
            $zanBase = $articleDetail['extend']['zan_base'] ?? 0;
            $zan2Base = $articleDetail['extend']['zan2_base'] ?? 0;

            $resData['article_info'] = [
                'nickname' => $nickname,
                'avatar' => $avatar,
                'user_des' => $userDes,
                'create_time' => Util::timeToStr($articleDetail['create_time']),
                'title' => $articleDetail['title'],
                'comment_num' => $articleDetail['comment_num'] + $commentBase,
                'photo_list' => $articleDetail['photos'],
                'isself' => $isSelf,
//                'author_id' => $articleDetail['uid'], // 作者用户ID
                'avatar_adorn' => $adorn['avatar_adorn'],
                'tag' => $adorn['tag'],
                'badge' => $adorn['badge'],
                'zan_num' => $articleDetail['zan_num'] + $zanBase,
                'zan_num2' => $articleDetail['zan_num2'] + $zan2Base,
                'is_zan' => isset($zanData[$id]) && $zanData[$id] ? (int)$zanData[$id] : 0,  // 赞同｜反对
            ];
            // 阅读数 新增
            $astrFortuneArticleModel->changeArticleInfo([
                'id' => $id,
                'read_num' => $articleDetail['read_num'],
                'comment_num' => $articleDetail['comment_num'],
            ], 1, 1);
        }

        $articleCommentModel = new ArticleComment();
        // 获取用户评论列表信息
        $commentData = $articleCommentModel->getPageCommentList($uid, 6, $id, 2, $page);

        foreach ($commentData['data'] as $key => $item)
        {
            $commentData['data'][$key]['create_time'] = $item['time'];
        }

        $resData = array_merge($resData, $commentData);

        if (isset($articleDetail['comment_num']) && $commentData['total'] !== $articleDetail['comment_num'])
        {
            if ($page === 1)
            {
                $resData['article_info']['comment_num'] = $commentData['total'];
            }

            $astrFortuneArticleModel->UpdateData($id, ['comment_num' => $commentData['total']]);
        }

        return show(config('code.success'), '请求成功', $resData);
    }

    public function createArticle()
    {
        $pid = input('id/d', 0);
        $content = input('content/s', '');
        $photoListStr = input('photo_list/s', '');

        if (!$content)
        {
            return show(config('code.error'), '请输入动态内容');
        }

        if (mb_strlen($content) > 80)
        {
            return show(config('code.error'), '动态内容最多80字');
        }

        $photoList = json_decode($photoListStr, true);

        if (count($photoList) > 3)
        {
            return show(config('code.error'), '请求异常，最多插入三张图片～');
        }

        if ($this->user['no_comment'])
        {
            return show(202, '发布动态失败，已被禁止发布动态');
        }

        if (Util::commentCheck($this->user['id'], [
            'pid' => $pid,
            'content' => $content,
        ], 10))
        {
            return show(config('code.error'), '别心急等一等～');
        }

        //阿里云 验证【title内容及图片】
        $res = AliyunFilterWord::checkText($content, 'question_pic_check');
        if ($res)
        {
            return show(config('code.error'), '问题中有敏感词');
        }
        $ossHost = Env::get('host.photo');
        foreach ($photoList as $photo)
        {
            $res = AliyunFilterWord::checkImg(1, $ossHost . $photo, 'question_pic_check');
            if ($res['status'] === false)
            {
                return show(config('code.error'), '图片包含' . $res['text']);
            }
        }

        $data = [
            'pid' => $pid,
            'uid' => $this->user['id'],
            'title' => $content,
            'photos' => $photoListStr,
            'create_time' => $this->request->time()
        ];

        $resId = (new Zl2AstrFortuneArticle())->SaveData($data);

        return show(config('code.success'), '请求成功', ['id' => $resId]);
    }

    /**
     * 删除 星运变动 动态
     */
    public function delArticle()
    {
        $id = input('id/d', 0);
        if (!$id)
        {
            return show(config('code.error'), '请求异常');
        }

        $astrFortuneArticleModel = new Zl2AstrFortuneArticle();

        $articleDetail = $astrFortuneArticleModel->getInfoById($id, ['pid', 'uid', 'status']);

        if (!$articleDetail || $articleDetail['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '动态不存在，删除失败～');
        }

        if ($articleDetail['status'] === -1)
        {
            CacheManage::getInstance()->setCacheConfig('astro_fortune.article')
                ->setCacheKeyDetail('user_list', $this->user['id'])
                ->delJudge($id, 'user_list');
            CacheManage::getInstance()->setCacheConfig('astro_fortune.article', $articleDetail['pid'])->delJudge($id);
            return show(config('code.success'), '讨论删除成功');
        }

        $astrFortuneArticleModel->UpdateData($id, ['status' => -1]);

        CacheManage::getInstance()->setCacheConfig('astro_fortune.article', $articleDetail['pid'])->delJudge($id);
        CacheManage::getInstance()->setCacheConfig('astro_fortune.article')->setCacheKeyDetail('user_list', $this->user['id'])->delJudge($id, 'user_list');

        return show(config('code.success'), '讨论删除成功');
    }

    /**
     * 星运变动 动态 同感与无感
     */
    public function articleZan()
    {
        $id = input('id/d', 0);
        $type = input('type/d', 0); // 0=>不同感不无感 1=>同感 2=>无感

        if (!$id)
        {
            return show(config('code.error'), '请求异常');
        }
        //验证是否重复操作
        if (Util::commentCheck($this->user['id'], ['id' => $id, 'type' => $type]))
        {
            return show(config('code.error'), '别心急，等一等');
        }

        $astrFortuneArticleModel = new Zl2AstrFortuneArticle();

        $articleDetail = $astrFortuneArticleModel->getInfoById($id, ['status', 'zan_num', 'zan_num2']);

        if (!$articleDetail || $articleDetail['status'] !== 0)
        {
            return show(config('code.error'), '服务异常，讨论不存在～');
        }
        unset($articleDetail['status']);

        $astrFortuneArticleZanModel = new Zl2AstrFortuneArticleZan();

        $zanData = $astrFortuneArticleZanModel->getZan($this->user['id'], [$id]);

        $oldZan = (int)(empty($zanData) ? 0 : $zanData);
        if ($type === $oldZan)
        {
            return show(config('code.success'), '操作成功', $articleDetail);
        }

        $d = [];
        if ($oldZan === 1)
        {
            $d['zan_num'] = $articleDetail['zan_num'] - 1;
            $articleDetail['zan_num'] = $articleDetail['zan_num'] - 1;
        }
        if ($oldZan === 2)
        {
            $d['zan_num2'] = $articleDetail['zan_num2'] - 1;
            $articleDetail['zan_num2'] = $articleDetail['zan_num2'] - 1;
        }
        if ($type === 1)
        {
            $d['zan_num'] = $articleDetail['zan_num'] + 1;
            $articleDetail['zan_num'] = $articleDetail['zan_num'] + 1;
        }
        if ($type === 2)
        {
            $d['zan_num2'] = $articleDetail['zan_num2'] + 1;
            $articleDetail['zan_num2'] = $articleDetail['zan_num2'] + 1;
        }

        $astrFortuneArticleZanModel->setZan($this->user['id'], $id, $type);

        $astrFortuneArticleModel->UpdateData($id, $d);

        return show(config('code.success'), '操作成功', $articleDetail);
    }

    /**
     * 星运变动 动态 评论或评论回复
     * @return Json
     */
    public function articleComment()
    {
        $id = input('id/d', 0);
        $type = input('type/d', 0);
        $content = trim(htmlspecialchars(input('content/s', '')));
        $pid = input('pid/d', 0);
        $uid = $this->user['id'];

        $n = $type === 1 ? '评论' : '评论回复';
        if ($content === '')
        {
            return show(config('code.error'), $n . '内容不能为空');
        }

        if (!$id)
        {
            return show(config('code.error'), '请求异常');
        }

        if ($this->user['no_comment'])
        {
            return show(config('code.error'), $n . '失败，已被禁止' . $n);
        }
        $adorn = Util::getUserAdorn($this->user['id']);

        if ($type === 1)
        {
            $astrFortuneArticleModel = new Zl2AstrFortuneArticle();
            $articleDetail = $astrFortuneArticleModel->getInfoById($id, ['status', 'read_num', 'comment_num']);
            if (!$articleDetail || $articleDetail['status'] !== 0)
            {
                return show(config('code.error'), '动态内容不存在～');
            }

            $data = [
                'aid' => $id,
                'uid' => $uid,
                'content' => $content,
                'type' => 6,    //类型 1=>星文评论，2=>女神动态评论，3=>女神专区评论 必传 5=>星座讨论
                'status' => 0   // 状态 0 正常 -1 删除
            ];
            $res = (new ArticleComment())->commentAdd($this->user, $data);

            if ($res['status'])
            {
                // 阅读数 新增
                $astrFortuneArticleModel->changeArticleInfo([
                    'id' => $id,
                    'read_num' => $articleDetail['read_num'],
                    'comment_num' => $articleDetail['comment_num'],
                ], 2, 1);

                $rData = [
                    'id' => $res['id'],
                    'avatar' => $this->user['avatar'],
                    'nickname' => $this->user['nickname'],
                    'time' => '刚刚',
                    'create_time' => '刚刚',
                    'content' => htmlspecialchars_decode($content),
                    'reply_num' => 0,
                    'good_num' => 0,
                    'is_good' => 0,
                    'vip' => (new ZlUserVip())->getUserVipLevel($this->user['id']),
                    'is_owner' => 1,
                    'reply_list' => []
                ];
                $rData = array_merge($rData, $adorn);
                return show(config('code.success'), '评论成功', $rData);
            }
            return show(config('code.error'), $res['msg']);
        } else
        {
            // 评论详情
            $commentInfo = current((new ArticleComment())->batchGetInfo([$id], ['uid']));
            if (!$commentInfo)
            {
                return show(config('code.error'), '数据不存在');
            }

            // 判断 用户是否允许回复他
            if ($pid)
            {   // 回复->评论回复
                // 获取回复的 评论回复用户uid
                $replyUid = (new ArticleCommentReply())->getInfoById($pid, ['uid1']);
                if ($replyUid['uid1'] != $this->user['id'])
                {   // 不是回复自己
                    $replyStatus = (new UserPush())->getUserReplyStatus((int)$replyUid['uid1']); // 是否允许回复自己 true 允许 false 不允许
                    if (!$replyStatus)
                    {   // 不允许回复
                        return show(config('code.error'), '对方关闭了评论回复');
                    }
                }
            } else
            {   // 回复评论
                if ($commentInfo['uid'] != $this->user['id'])
                {   // 不是自己评论自己事
                    $replyStatus = (new UserPush())->getUserReplyStatus((int)$commentInfo['uid']); // 是否允许回复自己 true 允许 false 不允许
                    if (!$replyStatus)
                    {   // 不允许回复
                        return show(config('code.error'), '对方关闭了评论回复');
                    }
                }
            }

            $data = [
                'comment_id' => $id,
                'pid' => $pid,
                'content' => $content,
                'uid' => (int)$this->user['id'],
                'status' => 0   // 状态 0 正常 -1 删除
            ];

            $res = (new ArticleCommentReply())->addCommentReply($this->user, $data);

            if ($res['status'])
            {
                $rData = [
                    'id' => $res['id'],
                    'avatar' => $this->user['avatar'],
                    'nickname1' => $this->user['nickname'],
                    'nickname2' => $pid ? $res['nickname2'] : null,
                    'time' => '刚刚',
                    'create_time' => '刚刚',
                    'content' => htmlspecialchars_decode($content),
                    'content_type' => 1,
                    'good_num' => 0,
                    'is_good' => 0,
                    'is_owner' => 1,
                    'vip' => (new ZlUserVip())->getUserVipLevel($this->user['id']),
                ];
                $rData = array_merge($rData, $adorn);
                return show(config('code.success'), '评论成功', $rData);
            }

            return show(config('code.error'), $res['msg']);
        }
    }
}